package com.unsafe5_lock6;
//1、编写的资源类
class Ticket {

    private int ticket = 100;

    public void sale() {
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() +
                    "卖出一张票，票号：" + ticket);
            ticket--;
        } else {
            throw new RuntimeException("没有票了");
        }
    }

    public int getTicket() {
        return ticket;
    }

}
//同步代码块
public class SaleTicketDemo5 {
    public static void main(String[] args) {
//      2、创建资源对象
        Ticket ticket = new Ticket();
//        3、启动多个线程操作资源类对象
        Thread thread1 = new Thread("窗口1"){
            @Override
            public void run() {
//                不能给run()方法直接加锁，因为thread1、thread2、thread3的
//                三个run方法分别属于三个Thread类对象
//                run方法是费静态方法，那么锁对象默认选this，
//                那么锁对象根本不是同一个
                while (true){
                    synchronized (ticket){
                        ticket.sale();
                    }
                }
            }
        };
        Thread thread2 = new Thread("窗口2"){
            @Override
            public void run() {
                while (true){
                    synchronized (ticket){
                        ticket.sale();
                    }
                }
            }
        };
        Thread thread3 = new Thread("窗口3"){
            @Override
            public void run() {
                while (true){
                    synchronized (ticket){
                        ticket.sale();
                    }
                }
            }
        };
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
